package id.co.shuba.spamobile.dialog;

import id.co.shuba.spamobile.R;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TimePicker;

import com.actionbarsherlock.app.SherlockActivity;

public class CustomTimePickerDialog extends SherlockActivity {
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {	
		super.onCreate(savedInstanceState);
		setContentView(R.layout.time_picker);		
		Intent intent = getIntent();
		String value = intent.getStringExtra("Time");	
					
		final TimePicker picker = (TimePicker)findViewById(R.id.picker);	
		picker.setIs24HourView(true);
		
		try {
			String[] values = value.split(":");
			int hour = Integer.parseInt(values[0]);
			int minute = Integer.parseInt(values[1]);
			
			if (hour > 23 && minute != 0)
				throw new Exception();
			if (minute > 59)
				throw new Exception();
			
			picker.setCurrentHour(hour);
			picker.setCurrentMinute(minute);
		} catch (Exception e) {			
		}
		
		Button btnSet = (Button)findViewById(R.id.btnSet);
		btnSet.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.putExtra("Time", toTimeString(picker.getCurrentHour(), picker.getCurrentMinute()));				
				setResult(RESULT_OK, intent);
				finish();
			}
		});
		Button btnCancel = (Button)findViewById(R.id.btnCancel);
		btnCancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();				
			}
		});
	}	
	
	private String toTimeString(int hour, int minute) {
		String h = String.valueOf(hour);
		String m = String.valueOf(minute);
		if (h.length()==1)h="0"+h;
		if (m.length()==1)m="0"+m;
		return h+":"+m;
	}
}
